#include<cstdio>
#include<unistd.h>
#include<fcntl.h>
#include<iostream>
#include<sys/timerfd.h>
#include<cstdint>
using namespace std;


int main()
{
   //1.创建定时器
   int timerfd = ::timerfd_create(CLOCK_MONOTONIC,0);
   if(timerfd < 0)
   {
       cerr << "timerfd create error!" << endl;
       exit(1);
   }
   //2.启动定时器
  struct itimerspec itime;
  itime.it_value.tv_sec = 1;//第一次超时
  itime.it_value.tv_nsec = 0;
  itime.it_interval.tv_sec = 3;//第一次超市之后的超时间隔
  itime.it_interval.tv_nsec = 0;
  int n = ::timerfd_settime(timerfd,0,&itime,NULL);
  if(n < 0)
  {
    cerr << "start timer error!" << endl;
    exit(2);
  }
  //3.测试
  while(true)
  {
    uint64_t times;
    int ret = ::read(timerfd,&times,sizeof(times));//写入数据之前会阻塞没有数据
    if(ret < 0)
    {
       cerr << "read error" << endl;
       exit(3);
    }
    printf("比上一次读取数据超时了%ld\n",times);
  }
  ::close(timerfd);
   return 0;
}
